package controller

import (
	"bytes"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/nfnt/resize"
	"github.com/skip2/go-qrcode"
	"image"
	"image/draw"
	"image/png"
	"log"
	"net/http"
)

func QrcodePage(c *gin.Context) {
	c.HTML(http.StatusOK, "qrcode.html", gin.H{})
}

func GenerateQrcode(c *gin.Context) {
	s := c.Query("text")
	logo := c.Query("logo")
	fmt.Println(logo)
	if logo != "" {
		resp, err := http.Get(logo)
		if err != nil {
			log.Printf("Get Image Error:%v\n", err)
			return
		}
		logoImg, _, err := image.Decode(resp.Body)
		if err != nil {
			log.Printf("Decode Image Error:%v\n", err)
			return
		}
		qrCode, err := qrcode.New(s, qrcode.Medium)
		if err != nil {
			log.Printf("qrcode.New Error:%v\n", err)
			return
		}
		bgImg := qrCode.Image(256)
		bgRGB := image.NewRGBA(bgImg.Bounds())
		draw.Draw(bgRGB, bgImg.Bounds(), bgImg, image.Pt(0, 0), draw.Over)

		logoImg = resize.Resize(20, 20, logoImg, resize.Lanczos3)
		offset := image.Pt((bgImg.Bounds().Max.X-logoImg.Bounds().Max.X)/2, (bgImg.Bounds().Max.Y-logoImg.Bounds().Max.Y)/2)
		draw.Draw(bgRGB, bgRGB.Bounds().Add(offset), logoImg, image.Pt(0, 0), draw.Over)

		buf := new(bytes.Buffer)
		err = png.Encode(buf, bgRGB)
		if err != nil {
			log.Printf("png.Encode Error:%v\n", err)
			return
		}
		c.Data(http.StatusOK, "image/png", buf.Bytes())
		return
	}
	qrcodePng, _ := qrcode.Encode(s, qrcode.Medium, 256)
	c.Data(http.StatusOK, "image/png", qrcodePng)
}
